package com.bnz.web.servlet;

import com.bnz.pojo.Cart;
import com.bnz.pojo.Product;
import com.sun.javafx.image.IntPixelGetter;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;


@WebServlet("/cart")

public class CartServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {

	}
	//根据请求参数进行页面的跳转
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到请求参数
		String cmd = req.getParameter("cmd");
		//根据参数跳转
		if(StringUtils.isNotBlank(cmd)){
			if("add".equals(cmd)){
				// 添加到购物车操作
				add(req,resp);
			}
			if("remove".equals(cmd)){
				// 移除某件商品
				remove(req,resp);
			}
			if("clear".equals(cmd)){
				// 清空购物车
				clear(req,resp);
			}
		}
	}

	//添加商品到购物车中
	private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到商品id
		String pidStr = req.getParameter("pid");
		//得到servletContext上下文对象
		ServletContext servletContext = this.getServletContext();
		//得到servletContext中的所有商品列表
		Map<Integer, Product> products = (Map<Integer, Product>) servletContext.getAttribute("products");
		//将请求id转换为整数
		Integer pid = new Integer(pidStr);
		HttpSession session = req.getSession();
		//根据key得到值
		Product product = products.get(pid);
		//得到购物车对象
		Cart cart = (Cart) session.getAttribute("cart");
		//如果没有购物车就创建一个
		if(cart == null){
			cart = new Cart();
		}
		//将商品添加到购物车中
		cart.addCart(product);
		//将购物车放到session中
		session.setAttribute("cart",cart);
		//进行页面的转发或重定向
		req.getRequestDispatcher("/cartlist.jsp").forward(req,resp);

	}
	//移除某件商品
	private void remove(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
		//得到商品id
		String pidStr = req.getParameter("pid");
		Integer pid = new Integer(pidStr);
		//得到购物车
		HttpSession session = req.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		//从购物车移除商品
		cart.removeCart(pid);
		//进行页面的转发或重定向
		req.getRequestDispatcher("/cartlist.jsp").forward(req,resp);
	}

	//清空购物车
	private void clear(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
		//得到购物车
		HttpSession session = req.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		//清空购物车
		cart.clearCart();
		//进行页面的转发或重定向
		req.getRequestDispatcher("/cartlist.jsp").forward(req,resp);
	}


}
